FROM node:20-alpine AS frontend-builder

WORKDIR /app

COPY package*.json ./

RUN npm install --only=production

COPY src/ ./src/
COPY public/ ./public/
COPY tailwind.config.js ./
COPY postcss.config.js ./

RUN npm run build

FROM node:20-alpine AS backend-builder

WORKDIR /app/server

COPY server/package*.json ./

RUN npm install --only=production

FROM node:20-alpine AS runtime

#RUN apk add --no-cache \
#    postgresql-client \
#    curl
RUN echo "https://mirrors.aliyun.com/alpine/v3.21/main/" > /etc/apk/repositories && \
    echo "https://mirrors.aliyun.com/alpine/v3.21/community/" >> /etc/apk/repositories && \
    apk add --no-cache postgresql-client curl

RUN addgroup -g 1001 -S nodejs && \
    adduser -S portfolio -u 1001

WORKDIR /app

COPY --from=backend-builder /app/server/node_modules ./server/node_modules
COPY server/ ./server/
# 删除可能存在的.env文件，使用Docker Compose环境变量
RUN rm -f ./server/.env

COPY --from=frontend-builder /app/build ./build

COPY portfolio-data.json ./

RUN mkdir -p /app/logs && \
    chown -R portfolio:nodejs /app

USER portfolio

EXPOSE 9080 9081

HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:9081/api/health || exit 1

CMD ["node", "server/server.js"]
